/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.api.message;

import io.iec.edp.caf.common.JSONSerializer;
import io.iec.edp.caf.commons.exception.CAFRuntimeException;
import io.iec.edp.caf.commons.exception.ExceptionLevel;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import org.springframework.util.StringUtils;

public class AggregateBizMsgException extends CAFRuntimeException {

  private static final String suCode = "pfcommon";
  private static final String exceptionCode = "Gsp_Cef_Common_0001";

  private static final String extendMsgKey = "UIMsg";

  public AggregateBizMsgException(List<IBizMessage> msgList) {
    super(suCode, exceptionCode, buildMessage(msgList), null, ExceptionLevel.Warning, true,
        buildExtensionMsg(msgList));
    Objects.requireNonNull(msgList, "msgList");
    if (msgList.stream().allMatch(msg -> msg.getLevel() != MessageLevel.Error)) {
      throw new IllegalArgumentException("没有Error级别的业务消息");
    }

    this.msgList = msgList;
  }

  private static HashMap<String, String> buildExtensionMsg(List<IBizMessage> msgList) {
    return new HashMap<String, String>() {{
      put(extendMsgKey, JSONSerializer.serialize(msgList));
    }};
  }

  private static String buildMessage(List<IBizMessage> msgList) {
    if (msgList == null || msgList.isEmpty()) {
      return "";
    }

    StringBuilder sb = new StringBuilder();
    msgList.stream().map(item -> buildMessage(item)).filter(item -> !StringUtils.isEmpty(item))
        .distinct().forEach(msg -> {
      if (sb.length() > 0) {
        sb.append(System.lineSeparator());
      }
      sb.append(msg);
    });
    return sb.toString();
  }

  private static String buildMessage(IBizMessage msg) {
//    if (!StringUtils.isEmpty(msg.getMessage())) {
      return msg.getMessage();
//    }
//    if (msg.getDetailMessages() == null || msg.getDetailMessages().isEmpty()) {
//      return null;
//    }
//
//    return buildMessage(msg.getDetailMessages());
  }

  private List<IBizMessage> msgList;

  public List<IBizMessage> getMessageList() {
    return msgList;
  }

  public void setMessageList(List<IBizMessage> msg) {
    msgList = msg;
  }
}
